package com.newhero.app.report.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.newhero.app.report.persistence.entity.Disclose;
import com.newhero.app.report.service.IDiscloseService;
import com.newhero.app.report.utils.DESFileUtil;
import com.newhero.app.report.utils.DesModleUtils;
import com.newhero.app.report.utils.StringSubStr;
import com.newhero.product.common.controller.BaseController;
import com.newhero.product.common.util.GTime;
import com.newhero.product.common.util.StringUtils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

 /**
 * @ClassName: DiscloseController
 * @Description: 访问控制类
 * @author zlf
 * @date 2018-09-07
 */
@Controller
@RequestMapping("/disclose")
public class ExportWordController extends BaseController {
	
	// word模板
	public static final String word_PeopleTemplate = "/exportReportPeople.ftl";
	public static final String word_UnitTemplate = "/exportReportUnit.ftl";
	// 存放模板的目录
	public static final String template_path = "/WEB-INF/ftl/report/template";
	// 临时文件
	public static final String word_temp = "/WEB-INF/ftl/report/template/temp.doc";

	 @Autowired 
    private IDiscloseService discloseServiceImpl;
	 
	@RequestMapping(value = "/exportWord", method ={RequestMethod.GET,RequestMethod.POST })
	public String executeExport(HttpServletRequest request,String discloseId,HttpServletResponse response) {
		

		try {

			Map<String,Object> dataMap = new HashMap<String,Object>();

			if (getData(request, response, discloseId,dataMap)) {

				File previewFile = new File(request.getSession()
						.getServletContext().getRealPath(word_temp));

				InputStream is = new FileInputStream(previewFile);

				response.reset();

				response.setContentType("application/vnd.ms-word;charset=UTF-8");

				response.setHeader("Content-Disposition",
						"attachment; filename=export.doc");

				OutputStream os = response.getOutputStream();

				byte[] b = new byte[1024];

				int len;

				while ((len = is.read(b)) != -1) {

					os.write(b, 0, len);

				}

				is.close();

				os.flush();

				os.close();

			}

		} catch (Exception e) {

			e.printStackTrace();

		}

		return null;

	}

	@SuppressWarnings("deprecation")
	public static Template configTemplate(HttpServletRequest request,
			String temp) {

		Template template = null;

		try {

			Configuration cfg = new Configuration();

			ServletContext application = request.getSession()
					.getServletContext();

			System.out.println(application.getRealPath(template_path));
			//加载模板路径文件夹
			cfg.setDirectoryForTemplateLoading(new java.io.File(application
					.getRealPath(template_path)));

			cfg.setObjectWrapper(new DefaultObjectWrapper());

			template = cfg.getTemplate(temp, "utf-8");

		} catch (Exception e) {

			e.printStackTrace();

		}

		return template;

	}

	public static void toPreview(HttpServletRequest request, String temp,
			Map<?, ?> root) {

		try {

			String previewPath = request.getSession().getServletContext()
					.getRealPath("")
					+ word_temp;

			Template tmplate = configTemplate(request, temp);

			FileOutputStream fis = new FileOutputStream(previewPath);

			Writer out = new OutputStreamWriter(fis, "utf-8");

			tmplate.process(root, out);

			out.flush();
			out.close();

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public boolean getData(HttpServletRequest request,
			HttpServletResponse response,String discloseId, Map<String,Object> dataMap) throws Exception {
		Disclose dis = discloseServiceImpl.selectById(discloseId);
		Disclose disclose = this.DiscloseEncryptAndDecrypt(dis,"1");
		//导出状态 2:已导出
		dis.setState(2);
		String ip = "";
		try{
			ip = StringSubStr.getRealIp();
			if(ip == null){
				ip = "0.0.0.0.0";
			}
		}catch(Exception re){
			ip = "0.0.0.0.0";
			re.printStackTrace();
		}
		dis.setExportIp(DESFileUtil.encryptStr(ip));
		dis.setExportDate(DESFileUtil.encryptStr(GTime.getTime(GTime.YYMMDDhhmmss)));
		discloseServiceImpl.updateById(dis);
		
		if(disclose.getMainContent1()!=null){
			disclose.setMainContent(disclose.getMainContent()+disclose.getMainContent1());
			if(disclose.getMainContent2()!=null){
				disclose.setMainContent(disclose.getMainContent()+disclose.getMainContent2());
				if(disclose.getMainContent3()!=null){
					disclose.setMainContent(disclose.getMainContent()+disclose.getMainContent3());
				}
			}
		}
		dataMap.put("kindName", disclose.getKindName());
		dataMap.put("year", disclose.getYear());
		dataMap.put("reportCode", disclose.getReportCode());
		dataMap.put("feedbackId", disclose.getFeedbackId());
		dataMap.put("mxcode", disclose.getMxcode());
		dataMap.put("mxname", disclose.getMxname());
		dataMap.put("disRegion", disclose.getDisRegion());
		dataMap.put("disName", disclose.getDisName());
		
		if(disclose.getDisSex() != null && disclose.getDisSex() == 0){
			dataMap.put("disSex", "女");
		}else{
			dataMap.put("disSex", "男");
		}
		
		dataMap.put("disUnit", disclose.getDisUnit());
		dataMap.put("disPost", disclose.getDisPost());
		dataMap.put("identityCard", disclose.getIdentityCard());
		dataMap.put("zipCode", disclose.getZipCode());
		dataMap.put("address", disclose.getAddress());
		dataMap.put("phone", disclose.getPhone());
		dataMap.put("telephone", disclose.getTelephone());
		dataMap.put("email", disclose.getEmail());
		dataMap.put("reportedName", disclose.getReportedName());
		if(disclose.getReportedSex() != null && disclose.getReportedSex() == 0){
			dataMap.put("reportedSex", "女");
		}else{
			dataMap.put("reportedSex", "男");
		}
		dataMap.put("reportedZzmm", disclose.getReportedZzmm());
		dataMap.put("reportedUnit", disclose.getReportedUnit());
		dataMap.put("reportedPost", disclose.getReportedPost());
		dataMap.put("reportedUnitLevel", disclose.getReportedUnitLevel());
		dataMap.put("problemName", disclose.getProblemName());
		dataMap.put("reportedRegion", disclose.getReportedRegion());
		dataMap.put("reportedLevel", disclose.getReportedLevel());
		dataMap.put("mainContent", disclose.getMainContent());
		dataMap.put("disDate", disclose.getDisDate());
		dataMap.put("discloseType", disclose.getDiscloseType());
		dataMap.put("rUname", disclose.getReplyUname());
		dataMap.put("rContent", disclose.getReplyContent());
		dataMap.put("rDate", disclose.getReplyDate());
		dataMap.put("levelName", disclose.getLevelName());
		
		String word_template = "";
		if(disclose.getDiscloseType() == 0){
			word_template = word_PeopleTemplate;
		}else{
			word_template = word_UnitTemplate;
		}

		toPreview(request, word_template, dataMap);
		return true;
	}
	
	/** 
     * 获取对象的所有属性值，对对象数据进行加密或者解密然后返回该对象 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 * 加密状态desState:0加密 1解密
	 * 
     * */  
    public Disclose DiscloseEncryptAndDecrypt(Disclose o,String desState) {  
    	 
    	Disclose obj = new Disclose();
    	String[] fieldNames= DesModleUtils.getFiledName(o);  
	    Object[] value=new Object[fieldNames.length]; 
	     
	     for(int i=0;i<fieldNames.length;i++){  
	    	 if("serialVersionUID".equals(fieldNames[i])){
	    		 continue;
	    	 }
	         value[i] = DesModleUtils.getFieldValueByName(fieldNames[i], o); 
	         try {
				Field field = Disclose.class.getDeclaredField(fieldNames[i]);
				field.setAccessible(true);
				//获取当前属性的  类型
				String type = field.getType().toString();
				if("class java.lang.String".equals(type) && !"discloseId".equals(fieldNames[i])&& !"dateOrder".equals(fieldNames[i])){
					String str = "";
					if(StringUtils.isNotBlank((String) value[i])){
						if("0".equals(desState)){
							//加密对象值
							str = DESFileUtil.encryptStr((String) value[i]);
						}else{
							//解密对象值
							str = DESFileUtil.decryptStr((String) value[i]);
						}
						
					}
					field.set(obj, str);
				}else{
					field.set(obj, value[i]);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
	     }  

	     return obj;  
    } 
}
